package com.bdzl.auth.controller;


import com.bdzl.auth.common.utils.*;
import com.bdzl.auth.service.LoginService;
import com.bdzl.auth.service.UserService;
import com.bdzl.auth.servicefeign.MobileCodeFeignService;
import com.bdzl.auth.util.SmsUtil;
import com.bdzl.pub.controller.BaseController;
import com.bdzl.pub.entity.sys.MobileCodeDO;
import com.bdzl.pub.entity.sys.UserDO;
import com.bdzl.pub.util.param.R;
import com.bdzl.pub.string.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.bdzl.auth.common.utils.JwtUtil.getUsername;


/**
* @Description: TODO 登录接口
* @Author: Ming
* @Date: 2021/4/27 11:24
*/

@Controller
@RequestMapping("/bdzl/logins")
public class LoginController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ImageValidateController imageValidateController;
    @Autowired
    private LoginService loginService;
    @Autowired
    private MobileCodeFeignService mobileCodeFeignService;


    /**
    * @Description: TODO 获取token
    * @param userDO
    * @return: com.bdzl.pub.util.param.R
    * @Author: Ming
    * @Date: 2021/5/17 15:25
    */
    @PostMapping(value = "/getToken")
    @ResponseBody
    public R getToken(@RequestBody UserDO userDO){
        String username = userDO.getUserLgname();
        String password = userDO.getUserPwd();

        //update-end-author:taoyan date:20190828 for:校验验证码

        //1. 校验用户是否有效
        //update-begin-author:wangshuai date:20200601 for: 登录代码验证用户是否注销bug，if条件永远为false
        UserDO sysUser = userService.getByUserLgname(username);
        R r = userService.checkUserIsEffective(sysUser);
        if(!R.ok().equals(r)) {
            return r;
        }
        //2. 校验用户名或密码是否正确
        password = MD5Utils.encrypt(username, password);
        String syspassword = sysUser.getUserPwd();
        if (!syspassword.equals(password)) {
            return R.error("账户名或密码错误！");
        }
        // 生成token
        String token = JwtUtil.sign(username, syspassword);
        // 设置token缓存有效时间
        redisUtil.set("user_token_" + token, token);
        redisUtil.expire("user_token_" + token, JwtUtil.EXPIRE_TIME*20);
        r.put("token",token); //登录token
        return r;
    }

    /**
     * 登录接口
     * @param user 用户
     * @param request
     * @return
     */
    @PostMapping(value = "/login")
    @ResponseBody
    public R login(@RequestBody UserDO user, HttpServletRequest request){
        //验证验证码    使用userid字段传验证码x坐标轴
        imageValidateController.check(user.getUserId(),request);
        //userid 置空
        user.setUserId(null);
        //调用登录验证
        R login = loginService.login(user);
        //调用登录接口
        R r = loginService.userInfo(user, login);
        return r;
    }



    /**
     * 退出登录
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/logout")
    @ResponseBody
    public R logout(HttpServletRequest request, HttpServletResponse response) {
        return loginService.logout(request,response);
    }

    /**
     *验证账号是否存在
     * @param username 用户名
     * @return
     */
    @GetMapping("/checkAccountNumber")
    @ResponseBody
    public R checkAccountNumber(String username){
        Map param = new HashMap();
        //根据用户名获取用户
        UserDO userDO = userService.getByUserLgname(username);
        //用户为空 账号不存在
        if (userDO!=null){
            return R.ok();
        }
        return R.error("账号不存在");
    }

 /**
  * @Author Zhn
  * @Description //TODO 验证手机号是否绑定该账号
  * @Date 14:37 2021/5/11
  * @Param [phone, username] 手机号，  用户名
  * @return com.bdzl.pub.util.param.R
  **/
    @GetMapping("/forgetThePassword")
    @ResponseBody
    public R forgetThePassword(String phone,String username){
        //验证手机号长度是否为11位
        if (!StringUtils.verificationPhone(phone)){
            return R.error("请输入正确的手机号！");
        }
        //根据用户名获取用户
        UserDO userDO = userService.getByUserLgname(username);
        //根据手机号和账号绑定的身份信息确认忘记密码人员身份
        if (!userDO.getUserPhone().equals(phone)){
            return R.error("此手机号未绑定"+username+"，请核实后再输入手机号！");
        }
        //调用发送短信接口接口
        MobileCodeDO mobileCodeDO = new MobileCodeDO();
        mobileCodeDO = SmsUtil.sendSms(mobileCodeDO, phone, "SMS_133920040");
        if (mobileCodeDO.getMcCode().equals("OFF")){
            return R.error("验证码发送失败！");
        }
        //把验证码保存3分钟
        redisUtil.set("verification"+phone,mobileCodeDO.getMcCode(),60*10);
        //补充短信发送的信息
        mobileCodeDO = loginService.getMobileCodeDO(mobileCodeDO,username,"SMS_133920040",phone,10);
        mobileCodeFeignService.save(mobileCodeDO);
        return R.ok();
    }

   /**
    * @Author Zhn
    * @Description //TODO 验证手机验证码
    * @Date 14:38 2021/5/11
    * @Param [phone, verificationCode] 手机号，  验证码
    * @return com.bdzl.pub.util.param.R
    **/
    @GetMapping("/checkVerificationCode")
    @ResponseBody
    public R checkVerificationCode(String phone,String verificationCode){
        //验证手机号长度是否为11位
        if (!StringUtils.verificationPhone(phone)){
            return R.error("请输入正确的手机号！");
        }
        //判断输入的验证码是否正确
        if (redisUtil.get("verification"+phone)==null){
            return R.error("验证码已过期,请重新获取验证码！");
        }
        //根据手机号 找到存储的验证码
        String s = redisUtil.get("verification"+phone).toString();
        if (s.equals(verificationCode)){
            return R.ok();
        }
        return R.error("验证码错误,请输入验证码！");
    }
    /**
     * @Author Zhn
     * @Description //TODO 验证手机验证码
     * @Date 14:38 2021/5/11
     * @Param [phone, verificationCode] 手机号，  验证码
     * @return com.bdzl.pub.util.param.R
     **/
    @PostMapping("/checkPhoneCode")
    @ResponseBody
    public R checkPhoneCode(String conMobile,String verificationCode){
        //判断输入的验证码是否正确
        if (redisUtil.get("verification"+conMobile)==null){
            return R.error("验证码已过期,请重新获取验证码！");
        }
        //根据手机号 找到存储的验证码
        String s = redisUtil.get("verification"+conMobile).toString();
        System.out.println("------------存的验证码："+s+"传的验证码："+verificationCode);
        if (s.equals(verificationCode)){
            return R.ok();
        }
        return R.error("验证码错误,请输入验证码！");
    }

 /**
  * @Author Zhn
  * @Description //TODO 修改密码
  * @Date 14:39 2021/5/11
  * @Param [password, username] 新密码，用户名
  * @return com.bdzl.pub.util.param.R
  **/
    @GetMapping("/changePassword")
    @ResponseBody
    public R changePassword(String password, String username){
        //根据用户名找到对应用户的账号
        UserDO byUserLgname = userService.getByUserLgname(username);
        //加密密码
        password = MD5Utils.encrypt(username, password);
        //修改密码
        byUserLgname.setUserPwd(password);
        //保存
        if (userService.update(byUserLgname)>0){
            return R.ok();
        }
        return R.error("修改失败");
    }

    /**
     * @Author Zhn
     * @Description //TODO 发送手机号验证码
     * @Date 14:37 2021/5/11
     * @Param [phone, time] 手机号，  时长
     * @return com.bdzl.pub.util.param.R
     **/
    @GetMapping("/Send")
    @ResponseBody
    public R Send(String phone,String id,Integer time,HttpServletRequest request){
        String accessToken = request.getHeader("X-Access-Token");
        String username = JwtUtil.getUsername(accessToken);//获取用户名
        //验证手机号长度是否为11位
        if (!StringUtils.verificationPhone(phone)){
            return R.error("请输入正确的手机号！");
        }
        //调用发送短信接口接口
        MobileCodeDO mobileCodeDO = new MobileCodeDO();
        mobileCodeDO = SmsUtil.sendSms(mobileCodeDO, phone, id);
        System.out.println("_____________生成的验证码"+mobileCodeDO.getMcCode());
        if (mobileCodeDO.getMcCode().equals("OFF")){
            return R.error("验证码发送失败！");
        }
        if (time==null){
            //把验证码保存10分钟
            redisUtil.set("verification"+phone,mobileCodeDO.getMcCode(),60*10);
        }else {
            //自定义时长
            redisUtil.set("verification"+phone,mobileCodeDO.getMcCode(),60*time);
        }
        //补充短信发送的信息
        mobileCodeDO = loginService.getMobileCodeDO(mobileCodeDO,username,id,phone,time);
        mobileCodeFeignService.save(mobileCodeDO); //保存
        return R.ok();
    }




}
